package com.xjoyt.pay.master.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.Predicate;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;

import com.xjoyt.pay.abstracts.AbstractDao;
import com.xjoyt.pay.dto.PageParam;
import com.xjoyt.pay.dto.PageResult;
import com.xjoyt.pay.master.dao.CompanyCheckoutRepositoryCustom;
import com.xjoyt.pay.master.params.CompanyCheckoutPageParam;
import com.xjoyt.pay.master.po.CompanyCheckout;
import com.xjoyt.pay.master.repository.CompanyCheckoutRepository;

public class CompanyCheckoutRepositoryImpl extends AbstractDao implements CompanyCheckoutRepositoryCustom {

	@Autowired
	private CompanyCheckoutRepository repository;

	@Override
	public PageResult<CompanyCheckout> loadPage(PageParam<CompanyCheckoutPageParam> param) {
		Pageable pageable = getPageable(param);
		Specification<CompanyCheckout> spec = getSpecification(param.query);
		Page<CompanyCheckout> pageReuslt = repository.findAll(spec, pageable);
		return new PageResult<>(pageReuslt.getTotalElements(), pageReuslt.getContent());
	}

	private Specification<CompanyCheckout> getSpecification(CompanyCheckoutPageParam param) {
		Specification<CompanyCheckout> spec = (root, query, cb) -> {
			if (param == null) {
				return null;
			}
			List<Predicate> list = new ArrayList<>();
			if (StringUtils.isNotBlank(param.parentId)) {
				list.add(cb.like(root.get("company").get("path"), "%" + param.parentId + "%"));
			}
			if (StringUtils.isNotBlank(param.path)) {
				list.add(cb.or(cb.equal(root.get("company").get("id"), param.path),
						cb.like(root.get("company").get("path"), "%" + param.path + "%")));
			}

			if (StringUtils.isNotBlank(param.query)) {

				for (String string : param.query.split(" ")) {
					if (StringUtils.isBlank(string))
						continue;
					String like = "%" + string + "%";
					list.add(cb.or(cb.like(root.get("company").get("name"), like)));
				}
			}

			if (param.startDate != null && param.endDate != null) {
				param.startDate = toStartDate(param.startDate);
				param.endDate = toEndDate(param.endDate);
				list.add(cb.between(root.get("addedDate"), param.startDate, param.endDate));
			}

			if (CollectionUtils.isNotEmpty(list))
				query.where(cb.and(list.toArray(new Predicate[list.size()])));

			return null;
		};

		return spec;
	}
}
